def generate_merge_statement(table_a, table_b, columns_a, primary_keys_a, columns_b, primary_keys_b, filter_condition=None, dblink=None):
    """
    生成 SQL MERGE 语句
    
    参数:
        table_a: 目标表名
        table_b: 源表名
        columns_a: 目标表的列名列表
        primary_keys_a: 目标表的主键列名列表
        columns_b: 源表的列名列表
        primary_keys_b: 源表的主键列名列表
        filter_condition: 筛选条件，用于过滤表B的数据（可选）
        dblink: 数据库链接信息，用于表B是远程表的情况（可选）
    
    返回:
        字典，包含状态和结果信息
    """
    # 参数验证
    if not all([table_a, table_b, columns_a, columns_b]):
        return {"success": False, "error": "表名和列名列表不能为空", "statement": None}
    
    # 处理主键为空的情况
    if not primary_keys_a and not primary_keys_b:
        # 如果两个表的主键都为空，则认为所有列都是主键
        primary_keys_a = columns_a
        primary_keys_b = columns_b
    elif not primary_keys_a or not primary_keys_b:
        return {"success": False, "error": "一个表有主键而另一个表没有", "statement": None}
    
    # 验证主键数量和名称是否一致
    if len(primary_keys_a) != len(primary_keys_b):
        return {"success": False, "error": "两个表的主键数量不一致", "statement": None}
    
    # 检查主键兼容性：确保A的主键都是B的主键
    for pk_a in primary_keys_a:
        if pk_a not in columns_b:
            return {"success": False, "error": f"目标表的主键 '{pk_a}' 不在源表中", "statement": None}
    
    # 构建列映射关系
    column_mapping = {}
    for col_a in columns_a:
        if col_a in columns_b:
            column_mapping[col_a] = col_a
        else:
            return {"success": False, "error": f"目标表的列 '{col_a}' 不在源表中", "statement": None}
    
    # 验证主键映射
    for pk_a, pk_b in zip(primary_keys_a, primary_keys_b):
        if column_mapping.get(pk_a) != pk_b:
            return {"success": False, "error": f"主键映射不匹配 - 目标表 '{pk_a}' 映射到源表 '{pk_b}'", "statement": None}
    
    # 构建 MERGE 语句
    merge_parts = []
    
    # MERGE 头部
    merge_parts.append(f"MERGE INTO {table_a} A")
    
    # USING 部分，处理筛选条件和 DBlink
    if dblink:
        # 使用 DBlink 格式的表名
        full_table_b = f"{table_b}@{dblink}"
        
        if filter_condition:
            # 使用子查询并应用筛选条件
            column_list = ', '.join([f"B.{col}" for col in columns_b])
            merge_parts.append(f"USING (SELECT {column_list} FROM {full_table_b} WHERE {filter_condition}) B")
        else:
            # 直接使用源表（通过 DBlink）
            merge_parts.append(f"USING {full_table_b} B")
    else:
        # 常规表名处理
        if filter_condition:
            # 使用子查询并应用筛选条件
            column_list = ', '.join([f"B.{col}" for col in columns_b])
            merge_parts.append(f"USING (SELECT {column_list} FROM {table_b} WHERE {filter_condition}) B")
        else:
            # 直接使用源表
            merge_parts.append(f"USING {table_b} B")
    
    # ON 条件部分（主键匹配）
    on_conditions = []
    for pk_a, pk_b in zip(primary_keys_a, primary_keys_b):
        on_conditions.append(f"A.{pk_a} = B.{pk_b}")
    
    merge_parts.append(f"ON ({' AND '.join(on_conditions)})")
    
    # WHEN MATCHED 部分（更新操作）
    update_columns = []
    for col_a in columns_a:
        # 跳过主键列的更新
        if col_a not in primary_keys_a:
            col_b = column_mapping[col_a]
            update_columns.append(f"A.{col_a} = B.{col_b}")
    
    if update_columns:
        merge_parts.append("WHEN MATCHED THEN")
        merge_parts.append(f"  UPDATE SET {', '.join(update_columns)}")
    
    # WHEN NOT MATCHED 部分（插入操作）
    insert_columns = []
    values = []
    
    for col_a in columns_a:
        col_b = column_mapping[col_a]
        insert_columns.append(f"A.{col_a}")
        values.append(f"B.{col_b}")
    
    if insert_columns and values:
        merge_parts.append("WHEN NOT MATCHED THEN")
        merge_parts.append(f"  INSERT ({', '.join(insert_columns)})")
        merge_parts.append(f"  VALUES ({', '.join(values)})")
    
    # 添加分号结束语句
    merge_parts.append(";")
    
    # 组合完整语句
    statement = "\n".join(merge_parts).strip()
    
    # 返回成功结果
    return {"success": True, "error": None, "statement": statement}


# 示例用法
if __name__ == "__main__":
    # 示例 1: 标准情况
    print('示例 1: 标准情况')
    result = generate_merge_statement(
        table_a="users",
        table_b="temp_users",
        columns_a=["id", "name", "email", "created_at"],
        primary_keys_a=["id"],
        columns_b=["id", "name", "email", "created_at"],
        primary_keys_b=["id"]
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 2: 所有列都是主键
    print('示例 2: 所有列都是主键')
    result = generate_merge_statement(
        table_a="products",
        table_b="temp_products",
        columns_a=["sku", "name", "price"],
        primary_keys_a=[],  # 空主键列表
        columns_b=["sku", "name", "price"],
        primary_keys_b=[]   # 空主键列表
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 3: 错误情况 - 主键数量不一致
    print('示例 3: 错误情况 - 主键数量不一致')
    result = generate_merge_statement(
        table_a="orders",
        table_b="temp_orders",
        columns_a=["order_id", "user_id", "amount", "date"],
        primary_keys_a=["order_id"],
        columns_b=["order_id", "user_id", "amount", "date"],
        primary_keys_b=["order_id", "user_id"]  # 两个主键
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 4: 添加筛选条件
    print('示例 4: 添加筛选条件')
    result = generate_merge_statement(
        table_a="users",
        table_b="temp_users",
        columns_a=["id", "name", "email", "status", "updated_at"],
        primary_keys_a=["id"],
        columns_b=["id", "name", "email", "status", "updated_at"],
        primary_keys_b=["id"],
        filter_condition="status = 'active' AND updated_at > '2023-01-01'"
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 5: A的列是B的列的子集
    print('示例 5: A的列是B的列的子集')
    result = generate_merge_statement(
        table_a="users",
        table_b="temp_users",
        columns_a=["id", "name", "email"],  # A表只有3列
        primary_keys_a=["id"],
        columns_b=["id", "name", "email", "status", "updated_at"],  # B表有5列
        primary_keys_b=["id"]
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 6: A的列是B的列的子集，且主键匹配
    print('示例 6: A的列是B的列的子集，且主键匹配')
    result = generate_merge_statement(
        table_a="orders_summary",
        table_b="orders_detail",
        columns_a=["order_id", "user_id", "total_amount"],  # A表是汇总表
        primary_keys_a=["order_id"],
        columns_b=["order_id", "user_id", "product_id", "quantity", "price", "total_amount", "order_date"],  # B表是明细表
        primary_keys_b=["order_id"]
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 7: 表B是通过DBlink访问的远程表
    print('示例 7: 表B是通过DBlink访问的远程表')
    result = generate_merge_statement(
        table_a="local_users",
        table_b="remote_users",
        columns_a=["id", "name", "email"],
        primary_keys_a=["id"],
        columns_b=["id", "name", "email", "status"],
        primary_keys_b=["id"],
        dblink="remote_db_link"
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")
    
    # 示例 8: 表B是通过DBlink访问的远程表，且有筛选条件
    print('示例 8: 表B是通过DBlink访问的远程表，且有筛选条件')
    result = generate_merge_statement(
        table_a="local_products",
        table_b="remote_products",
        columns_a=["sku", "name", "price"],
        primary_keys_a=["sku"],
        columns_b=["sku", "name", "price", "stock", "last_updated"],
        primary_keys_b=["sku"],
        filter_condition="stock > 0 AND last_updated > SYSDATE - 7",
        dblink="remote_db_link"
    )
    print(result['statement'] + "\n" if result['success'] else result['error'] + "\n")